package com.maruping.disk.file.control;

import com.alibaba.fastjson.JSON;
import com.maruping.disk.file.entity.SearchFileEntity;
import com.maruping.disk.file.service.FileService;
import com.maruping.disk.file.service.FileIoService;
import com.maruping.disk.mybatis.entity.PtFileEntity;
import com.maruping.disk.mybatis.flexigrid.PagingEntity;
import com.maruping.disk.mybatis.flexigrid.TblResponseEntity;
import com.maruping.disk.spring.control.BaseController;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.annotation.Secured;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/file")
public class FileController extends BaseController {
    @Resource
    private FileService fileService;

    @Resource
    private FileIoService fileIoService;

    @RequestMapping("/fileAll")
    public String fileAll(){
        return "file/filePage";
    }
    @RequestMapping("/syncFileData")
    @ResponseBody
    public String syncFileData(){
        fileIoService.syncFileData();
        return successJson("file.sync.data.success");
    }
    @RequestMapping("/queryFileInfoListByPage")
    @ResponseBody
    public String queryFileInfoListByPage(SearchFileEntity entity, PagingEntity paging){
        TblResponseEntity<PtFileEntity> tblResponseEntity = fileService.queryFileInfoListByPage(entity,paging);
        return JSON.toJSONString(tblResponseEntity);
    }


    @RequestMapping("/queryFileInfoById")
    @ResponseBody
    public String queryFileInfoById(@RequestParam("fileUuid") String fileUuid){

        PtFileEntity ptFileEntity = fileService.queryFileInfoById(fileUuid);
        return JSON.toJSONString(ptFileEntity);
    }

    @RequestMapping("/mkdirFileInfo")
    @ResponseBody
    public String mkdirFileInfo(@RequestParam("parentId") String parentId, @RequestParam("folderName") String folderName){

        fileIoService.mkdirFileInfo(parentId, folderName);
        return successJson("file.mkdir.success");
    }


    @RequestMapping("/uploadFile")
    @ResponseBody
    public String uploadFile(MultipartHttpServletRequest request, @RequestParam("parentId") String parentId) throws IOException {
        MultipartFile multipartFile = request.getFile("fileName");
        String fileName = multipartFile.getOriginalFilename();

        fileIoService.uploadFile(parentId, fileName,multipartFile.getInputStream());

        return successJson("file.upload.success");
    }

    // 新增：查询文件ACL权限接口
    @Secured("ROLE_file_acl_manage") // 权限控制
    @RequestMapping("/queryFileAcl")
    @ResponseBody
    public String queryFileAcl(@RequestParam("fileUuid") String fileUuid) {
        try {
            return JSON.toJSONString(fileIoService.queryFileAcl(fileUuid));
        } catch (Exception e) {
            return failJson("file.acl.query.fail", e.getMessage());
        }
    }

    // 新增：设置文件ACL权限接口
    @Secured("ROLE_file_acl_manage") // 权限控制
    @RequestMapping("/setFileAcl")
    @ResponseBody
    public String setFileAcl(
            @RequestParam("fileUuid") String fileUuid,
            @RequestParam("aclArray") String aclArray
    ) {
        try {
            fileIoService.setFileAcl(fileUuid, aclArray);
            return successJson("file.acl.set.success");
        } catch (IllegalArgumentException e) {
            return failJson("param.error", e.getMessage());
        } catch (RuntimeException e) {
            return failJson("file.acl.set.fail", e.getMessage());
        }
    }


    /**
     * 生成文件临时分享链接
     * @param fileUuid 文件唯一标识（用于权限校验）
     * @param obsKey OBS中的文件路径（如"a4.jpg"）
     * @return 包含分享链接的JSON
     */
    @RequestMapping("/generateShareUrl")
    @ResponseBody
    public String generateShareUrl(
            @RequestParam("fileUuid") String fileUuid,
            @RequestParam("obsKey") String obsKey) {
        try {
            // 1. 权限校验（可选：验证当前用户是否有权限分享该文件）
            // 2. 调用服务层生成临时链接（有效期1小时）
            String shareUrl = fileService.generateTemporaryShareUrl(obsKey, 60 * 60);
            // 3. 返回结果
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("shareUrl", shareUrl);
            return JSON.toJSONString(result);
        } catch (Exception e) {
            return failJson("生成分享链接失败：" + e.getMessage());
        }
    }


    @RequestMapping("/downFile/{fileUuid}")
    @ResponseBody
    public ResponseEntity<byte[]> downFile(@PathVariable("fileUuid") String fileUuid){

        ResponseEntity<byte[]> responseEntity = fileIoService.downFile(fileUuid);
        return responseEntity;
    }

    @RequestMapping("/getShareUrl")
    @ResponseBody
public String getShareUrl(@RequestParam("fileUuid") String fileUuid){
        String url=fileIoService.getShareUrl(fileUuid);
        return successJson("file.share.success",url);

}

    @RequestMapping("/getPngImage")
    @ResponseBody
    public ResponseEntity<byte[]> getPngImage(@RequestParam("fileUuid") String fileUuid) {
        try {
            // 1. 查询文件信息
            PtFileEntity file = fileService.queryFileInfoById(fileUuid);
            if (file == null) {
                return new ResponseEntity<>(HttpStatus.NOT_FOUND);
            }

            // 2. 校验是否为PNG
            if (!file.getFileName().toLowerCase().endsWith(".png")) {
                return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
            }

            // 3. 复用下载逻辑获取文件字节流
            ResponseEntity<byte[]> fileData = fileIoService.downFile(fileUuid);
            if (fileData.getBody() == null) {
                return new ResponseEntity<>(HttpStatus.NO_CONTENT);
            }

            // 4. 设置PNG响应头（支持预览）
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.IMAGE_PNG);
            headers.setContentDispositionFormData("inline", file.getFileName());

            return new ResponseEntity<>(fileData.getBody(), headers, HttpStatus.OK);
        } catch (Exception e) {
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

}
